package com.fbs.job.admin.core.scheduler;

import com.fbs.job.admin.core.config.FbsJobAdminConfig;
import com.fbs.job.admin.core.thread.*;
import com.fbs.job.core.biz.ExecutorBiz;
import com.fbs.job.core.biz.client.ExecutorBizClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class FbsJobScheduler {
    private static final Logger logger = LoggerFactory.getLogger(FbsJobScheduler.class);
    public void init() throws Exception {
        JobTriggerPoolHelper.toStart();
        // admin registry monitor run
        JobRegistryHelper.getInstance().start();

        JobFailHandleHelper.getInstance().start();

        // admin lose-monitor run ( depend on JobTriggerPoolHelper )
        JobCompleteHelper.getInstance().start();
        logger.info(">>>>>>>>> init fbs-job admin success.");

        // start-schedule  ( depend on JobTriggerPoolHelper )
        JobScheduleHelper.getInstance().start();
        JobLogReportHelper.getInstance().start();

    }

    public void destroy(){
        // admin lose-monitor stop
        JobCompleteHelper.getInstance().toStop();
        JobScheduleHelper.getInstance().toStop();
        JobTriggerPoolHelper.toStop();

        JobFailHandleHelper.getInstance().toStop();
        JobRegistryHelper.getInstance().toStop();
        JobLogReportHelper.getInstance().toStop();
    }



    // ---------------------- executor-client ----------------------
    private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<>();
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        // set-cache
        executorBiz = new ExecutorBizClient(address, FbsJobAdminConfig.getAdminConfig().getAccessToken());

        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }

}
